
import axios from 'axios';
import React, { useCallback, useEffect, useMemo, useReducer, useState } from 'react'
import { useParams } from 'react-router'
import flvjs from 'flv.js'
import dplayer from "dplayer"
import { Button, message } from 'antd';

import "./LiveRoom.scss"
import { httpGetLive, httpRunCode } from '../apis';
import LiveRoomVideo from '../components/LiveRoom/LiveRoomVideo';
import LiveRoomChat from '../components/LiveRoom/LiveRoomChat';
import { useSelector } from 'react-redux';
import LiveRoomCode from '../components/LiveRoom/LiveRoomCode';
import LiveRoomContro from '../components/LiveRoom/LiveRoomContro';
import { useCheckAndNavigate } from '../utils';


const initialState = {
    roomInfo: {},
    msgs: [],
    viewers: 0,
    codeEdit: false,
    ytext: {},
    codeType: "javascript",
    codeResult: {
        data: "",
        err: "",
        stderr: "",
    },
    pending: false,
}
  
function reducer(state,action) {
    let list;
    switch (action.type) {
        case "setroomInfo":
            let roomInfo = action.roomInfo;
            return {
                ...state,
                roomInfo
            };
        case "addMsg":
            const msgs = state.msgs
            return {
                ...state,
                msgs: [...msgs,action.msg]
            };
        case "clearMsgs":
            return {
                ...state,
                msgs: []
            }
        case "changeViewers":
            const viewers = action.viewers;
            return {
                ...state,
                viewers
            }
        case "setCodeEdit":
            const codeEdit = action.codeEdit;
            return {
                ...state,
                codeEdit
            }
        case "setYtext":
            const ytext = action.ytext;
            return {
                ...state,
                ytext
            }
        case "setCodeResult":
            const codeResult = action.codeResult;
            return  {
                ...state,
                codeResult
            }
        case "setCodeType": 
            const codeType = action.codeType;
            return {
                ...state,
                codeType
            }
        case "updatePending":
            const pending = action.pending;
            return {
                ...state,
                pending
            }
        default:
        return state;
    }
}

export default function LiveRoom(props) {
    useCheckAndNavigate();
    const params = useParams();
    const liveId = params.liveId;
    const [state,dispatcher] = useReducer(reducer,initialState);
    const roomInfo = state.roomInfo;
    const viewers = state.viewers;
    const user = useSelector(state=>state.user);
    useEffect(async ()=>{
        let data = {
            liveId
        };
        const res = await httpGetLive(data);
        dispatcher({
            type: "setroomInfo",
            roomInfo: res
        });
    },[liveId]);

    useEffect(()=>{
        dispatcher({
            type: "changeViewers",
            viewers: props.viewers
        });
    },[props.viewers]);

    const copyPushAddr = useCallback(()=>{
        const tool = document.createElement("div")
        document.getElementsByClassName("description")[0].appendChild(tool);
        tool.innerText = roomInfo.rmtpAddr;
        window.getSelection().selectAllChildren(tool);
        document.execCommand("Copy");
        document.getElementsByClassName("description")[0].removeChild(tool);
        message.success("复制推流地址成功~");
    },[roomInfo]);

    const runCode = async () => {
        let data = {};
        data.code = state.ytext.toJSON();
        data.type = state.codeType;
        dispatcher({
            type: "updatePending",
            pending: true
        })
        httpRunCode(data).then((res)=>{
            dispatcher({
                type: "setCodeResult",
                codeResult: res
            });
            dispatcher({
                type: "updatePending",
                pending: false
            });
        })
    }

    return (
        <div className='LiveRoom-container'>
            <header>
                <h1>{roomInfo.title}</h1>
                <span>直播间人数🧙🏻‍♂️:{viewers}</span>
                &nbsp;
                &nbsp;
                {
                    (roomInfo.liveId==="0" || roomInfo.ownerId === user.userId) && <Button type='primary' size='small' onClick={copyPushAddr}>复制推流地址</Button>
                }
            </header>
            <div className='main-container'>
                <LiveRoomVideo state={state}></LiveRoomVideo>
                <LiveRoomChat state={state} dispatcher={dispatcher}></LiveRoomChat>
                <LiveRoomContro state={state} dispatcher={dispatcher} runCode={runCode}></LiveRoomContro>
            </div>
            <div className='description'>
                <h4>简介</h4>
                <div className="description-content">{roomInfo.description}</div>
                
            </div>
            <LiveRoomCode state={state} yjsAddr={roomInfo.yjsAddr} dispatcher={dispatcher}></LiveRoomCode>
        </div>
    )
}
